{"componentChunkName":"component---src-templates-post-tsx","path":"/Express-study_1/","result":{"data":{"markdownRemark":{"html":"<p>Hello world 예제\n기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제와 달리 Express 생성기를 통해 얻게 되는 앱은 다양한 목적을 위한 여러 JavaScript 파일, Jade 템플리트 및 하위 디렉토리를 포함하는 전체 앱에 대한 스캐폴딩을 작성합니다.)\n먼저, myapp이라는 이름의 디렉토리를 작성한 후 이 디렉토리로 이동하여 npm init를 실행하십시오. 이후 설치 안내서에 따라 express를 종속 항목으로서 설치하십시오.\nmyapp 디렉토리에 app.js라는 이름의 파일을 작성한 후 다음과 같은 코드를 추가하십시오.</p>\n<p>var express = require('express');\nvar app = express();\napp.get('/', function (req, res) {\nres.send('Hello World!');\n});\napp.listen(3000, function () {\nconsole.log('Example app listening on port 3000!');\n});\n앱은 서버를 시작하며 3000번 포트에서 연결을 청취합니다. 앱은 루트 URL(/) 또는 라우트에 대한 요청에 “Hello World!”로 응답합니다. 다른 모든 경로에 대해서는 404 Not Found로 응답합니다.\nreq(요청) 및 res(응답)는 Node가 제공하는 동일한 오브젝트이며, 따라서 req.pipe(), req.on('data', callback) 그리고 Express의 관여가 필요 없는 다른 모든 항목을 호출할 수 있습니다.\n다음의 명령을 이용하여 앱을 실행하십시오.</p>\n<p>$ node app.js\n이후 브라우저에서 <a href=\"http://localhost:3000/%EC%9D%84\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/을</a> 로드하여 결과물을 확인하십시오.</p>\n<p>출처: <a href=\"https://expressjs.com/ko/starter/hello-world.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">https://expressjs.com/ko/starter/hello-world.html</a></p>\n<p>Express 애플리케이션 생성기\n애플리케이션의 골격을 신속하게 작성하려면 애플리케이션 생성기 도구인 express를 사용하십시오.\n다음의 명령을 이용해 express를 설치하십시오.</p>\n<p>$ npm install express-generator -g\n다음과 같이 -h 옵션을 이용해 명령의 옵션을 표시하십시오.</p>\n<p>$ express -h\nUsage: express [options][dir]\nOptions:\n-h, --help output usage information\n--version output the version number\n-e, --ejs add ejs engine support\n--hbs add handlebars engine support\n--pug add pug engine support\n-H, --hogan add hogan.js engine support\n--no-view generate without view engine\n-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)\n-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)\n--git add .gitignore\n-f, --force force on non-empty directory\n예를 들면, 다음의 예에서는 <em>myapp</em>라는 이름의 Express 앱을 현재 작업 디렉토리에 작성합니다.</p>\n<p>$ express --view=pug myapp\ncreate : myapp\ncreate : myapp/package.json\ncreate : myapp/app.js\ncreate : myapp/public\ncreate : myapp/public/javascripts\ncreate : myapp/public/images\ncreate : myapp/routes\ncreate : myapp/routes/index.js\ncreate : myapp/routes/users.js\ncreate : myapp/public/stylesheets\ncreate : myapp/public/stylesheets/style.css\ncreate : myapp/views\ncreate : myapp/views/index.pug\ncreate : myapp/views/layout.pug\ncreate : myapp/views/error.pug\ncreate : myapp/bin\ncreate : myapp/bin/www\n이후 다음과 같이 종속 항목을 설치하십시오.</p>\n<p><span class=\"katex\"><span class=\"katex-mathml\"><math><semantics><mrow><mi>c</mi><mi>d</mi><mi>m</mi><mi>y</mi><mi>a</mi><mi>p</mi><mi>p</mi></mrow><annotation encoding=\"application/x-tex\">cd myapp</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:0.8888799999999999em;vertical-align:-0.19444em;\"></span><span class=\"mord mathdefault\">c</span><span class=\"mord mathdefault\">d</span><span class=\"mord mathdefault\">m</span><span class=\"mord mathdefault\" style=\"margin-right:0.03588em;\">y</span><span class=\"mord mathdefault\">a</span><span class=\"mord mathdefault\">p</span><span class=\"mord mathdefault\">p</span></span></span></span> npm install\nMacOS 또는 Linux에서는 다음 명령을 사용하여 앱을 실행하십시오.</p>\n<p>$ DEBUG=myapp:* npm start\nWindows에서는 다음 명령을 사용하십시오.</p>\n<blockquote>\n<p>set DEBUG=myapp:* &#x26; npm start\n이후 브라우저에서 <a href=\"http://localhost:3000/%EC%9D%84\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/을</a> 로드하여 앱에 액세스하십시오.\n생성된 앱은 다음과 같은 디렉토리 구조를 갖습니다.</p>\n</blockquote>\n<p>.\n├── app.js\n├── bin\n│ └── www\n├── package.json\n├── public\n│ ├── images\n│ ├── javascripts\n│ └── stylesheets\n│ └── style.css\n├── routes\n│ ├── index.js\n│ └── users.js\n└── views\n├── error.pug\n├── index.pug\n└── layout.pug\n7 directories, 9 files\n생성기에 의해 작성된 앱 구조는 Express 앱을 구조화하는 여러 방법 중 하나에 불과합니다. 이러한 구조를 사용하거나 사용자의 요구사항에 가장 적합하도록 구조를 수정하십시오.</p>\n<p>출처: <a href=\"https://expressjs.com/ko/starter/generator.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">https://expressjs.com/ko/starter/generator.html</a></p>\n<p>기본 라우팅\n라우팅은 URI(또는 경로) 및 특정한 HTTP 요청 메소드(GET, POST 등)인 특정 엔드포인트에 대한 클라이언트 요청에 애플리케이션이 응답하는 방법을 결정하는 것을 말합니다.\n각 라우트는 하나 이상의 핸들러 함수를 가질 수 있으며, 이러한 함수는 라우트가 일치할 때 실행됩니다.\n라우트 정의에는 다음과 같은 구조가 필요합니다.</p>\n<p>app.METHOD(PATH, HANDLER)\n여기서,\n• app은 express의 인스턴스입니다.\n• METHOD는 HTTP 요청 메소드입니다.\n• PATH는 서버에서의 경로입니다.\n• HANDLER는 라우트가 일치할 때 실행되는 함수입니다.\n이 학습서에서는 app이라는 이름의 express 인스턴스가 작성되며 서버가 실행 중인 것으로 가정합니다. 앱의 작성 및 시작에 익숙하지 않은 경우에는 Hello world 예제를 참조하십시오.\n다음 예에서는 간단한 라우트의 정의를 설명합니다.\n홈 페이지에서 Hello World!로 응답:</p>\n<p>app.get('/', function (req, res) {\nres.send('Hello World!');\n});\n애플리케이션의 홈 페이지인 루트 라우트(/)에서 POST 요청에 응답:</p>\n<p>app.post('/', function (req, res) {\nres.send('Got a POST request');\n});\n/user 라우트에 대한 PUT 요청에 응답:</p>\n<p>app.put('/user', function (req, res) {\nres.send('Got a PUT request at /user');\n});\n/user 라우트에 대한 DELETE 요청에 응답:</p>\n<p>app.delete('/user', function (req, res) {\nres.send('Got a DELETE request at /user');\n});\n라우팅에 대한 자세한 내용을 확인하려면 라우팅 안내서를 참조하십시오.</p>\n<p>출처: <a href=\"https://expressjs.com/ko/starter/basic-routing.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">https://expressjs.com/ko/starter/basic-routing.html</a></p>\n<p>Express에서 정적 파일 제공\n이미지, CSS 파일 및 JavaScript 파일과 같은 정적 파일을 제공하려면 Express의 기본 제공 미들웨어 함수인 express.static을 사용하십시오.\n정적 자산이 포함된 디렉토리의 이름을 express.static 미들웨어 함수에 전달하면 파일의 직접적인 제공을 시작할 수 있습니다. 예를 들면, 다음과 같은 코드를 이용하여 public이라는 이름의 디렉토리에 포함된 이미지, CSS 파일 및 JavaScript 파일을 제공하십시오.</p>\n<p>app.use(express.static('public'));\n이제 다음과 같이 public 디렉토리에 포함된 파일을 로드할 수 있습니다.</p>\n<p><a href=\"http://localhost:3000/images/kitten.jpg\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/images/kitten.jpg</a>\n<a href=\"http://localhost:3000/css/style.css\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/css/style.css</a>\n<a href=\"http://localhost:3000/js/app.js\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/js/app.js</a>\n<a href=\"http://localhost:3000/images/bg.png\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/images/bg.png</a>\n<a href=\"http://localhost:3000/hello.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/hello.html</a>\nExpress는 정적 디렉토리에 대해 상대적으로 파일을 검색하며, 따라서 정적 디렉토리의 이름은 URL의 일부가 아닙니다.\n여러 개의 정적 자산 디렉토리를 이용하려면 다음과 같이 express.static 미들웨어 함수를 여러 번 호출하십시오.</p>\n<p>app.use(express.static('public'));\napp.use(express.static('files'));\nExpress는 express.static 미들웨어 함수를 이용해 정적 디렉토리를 설정한 순서대로 파일을 검색합니다.\nexpress.static 함수를 통해 제공되는 파일에 대한 가상 경로 접두부(파일 시스템 내에 해당 경로가 실제로 존재하지 않는 경우)를 작성하려면, 아래에 표시된 것과 같이 정적 디렉토리에 대한 마운트 경로를 지정하십시오.</p>\n<p>app.use('/static', express.static('public'));\n이제 /static 경로 접두부를 통해 public 디렉토리에 포함된 파일을 로드할 수 있습니다.</p>\n<p><a href=\"http://localhost:3000/static/images/kitten.jpg\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/static/images/kitten.jpg</a>\n<a href=\"http://localhost:3000/static/css/style.css\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/static/css/style.css</a>\n<a href=\"http://localhost:3000/static/js/app.js\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/static/js/app.js</a>\n<a href=\"http://localhost:3000/static/images/bg.png\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/static/images/bg.png</a>\n<a href=\"http://localhost:3000/static/hello.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">http://localhost:3000/static/hello.html</a>\n그러나 express.static 함수에 제공되는 경로는 node 프로세스가 실행되는 디렉토리에 대해 상대적입니다. Express 앱을 다른 디렉토리에서 실행하는 경우에는 다음과 같이 제공하기 원하는 디렉토리의 절대 경로를 사용하는 것이 더 안전합니다.</p>\n<p>app.use('/static', express.static(__dirname + '/public'));</p>\n<p>출처: <a href=\"https://expressjs.com/ko/starter/static-files.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">https://expressjs.com/ko/starter/static-files.html</a></p>\n<p>라우팅\n라우팅은 애플리케이션 엔드 포인트(URI)의 정의, 그리고 URI가 클라이언트 요청에 응답하는 방식을 말합니다. 라우팅에 대한 소개는 기본 라우팅을 참조하십시오.\n다음 코드는 매우 기본적인 라우트의 예입니다.</p>\n<p>var express = require('express');\nvar app = express();\n// respond with \"hello world\" when a GET request is made to the homepage\napp.get('/', function(req, res) {\nres.send('hello world');\n});\n라우트 메소드\n라우트 메소드는 HTTP 메소드 중 하나로부터 파생되며, express 클래스의 인스턴스에 연결됩니다.\n다음 코드는 앱의 루트에 대한 GET 및 POST 메소드에 대해 정의된 라우트의 예입니다.</p>\n<p>// GET method route\napp.get('/', function (req, res) {\nres.send('GET request to the homepage');\n});\n// POST method route\napp.post('/', function (req, res) {\nres.send('POST request to the homepage');\n});\nExpress는 HTTP 메소드에 해당하는 다음과 같은 라우팅 메소드를 지원합니다. get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch, search 및 connect.\n올바르지 않은 JavaScript 변수 이름으로 변환되는 메소드를 라우팅하려면 대괄호 표기법을 사용하십시오. 예를 들면 app['m-search']('/', function ... 등과 같습니다.\n특수한 라우팅 메소드인 app.all()은 어떠한 HTTP 메소드로부터도 파생되지 않습니다. 이 메소드는 모든 요청 메소드에 대해 한 경로에서 미들웨어 함수를 로드하는 데 사용됩니다.\n다음 예에서는, GET, POST, PUT 또는 DELETE 메소드를 사용하는 경우, 또는 http 모듈에서 지원되는 기타 모든 HTTP 요청 메소드를 사용하는 경우 등의 “/secret”에 대한 요청을 위하여 핸들러가 실행됩니다.</p>\n<p>app.all('/secret', function (req, res, next) {\nconsole.log('Accessing the secret section ...');\nnext(); // pass control to the next handler\n});\n라우트 경로\n라우트 경로는, 요청 메소드와의 조합을 통해, 요청이 이루어질 수 있는 엔드포인트를 정의합니다. 라우트 경로는 문자열, 문자열 패턴 또는 정규식일 수 있습니다.\nExpress는 라우트 경로의 일치를 위해 path-to-regexp를 사용합니다. 라우트 경로를 정의할 수 있는 모든 가능성을 확인하려면 path-to-regexp 문서를 참조하십시오. Express Route Tester는 기본적인 Express 라우트의 테스트를 위한 편리한 도구이지만, 패턴 일치는 지원하지 않습니다.\n조회 문자열은 라우트 경로의 일부가 아닙니다.\n문자열을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다.\n다음의 라우트 경로는 요청을 루트 라우트 /에 일치시킵니다.</p>\n<p>app.get('/', function (req, res) {\nres.send('root');\n});\n다음의 라우트 경로는 요청을 /about에 일치시킵니다.</p>\n<p>app.get('/about', function (req, res) {\nres.send('about');\n});\n다음의 라우트 경로는 요청을 /random.text에 일치시킵니다.</p>\n<p>app.get('/random.text', function (req, res) {\nres.send('random.text');\n});\n문자열 패턴을 기반으로 하는 라우트 경로의 몇 가지 예는 다음과 같습니다.\n다음의 라우트 경로는 acd 및 abcd와 일치합니다.</p>\n<p>app.get('/ab?cd', function(req, res) {\nres.send('ab?cd');\n});\n다음의 라우트 경로는 abcd, abbcd 및 abbbcd 등과 일치합니다.</p>\n<p>app.get('/ab+cd', function(req, res) {\nres.send('ab+cd');\n});\n다음의 라우트 경로는 abcd, abxcd, abRABDOMcd 및 ab123cd 등과 일치합니다.</p>\n<p>app.get('/ab<em>cd', function(req, res) {\nres.send('ab</em>cd');\n});\n다음의 라우트 경로는 /abe 및 /abcde와 일치합니다.</p>\n<p>app.get('/ab(cd)?e', function(req, res) {\nres.send('ab(cd)?e');\n});\n?, +, * 및 () 문자는 정규식 문자의 서브세트입니다. 하이픈(-) 및 점(.)은 문자열 기반 경로에 의해 문자 그대로 해석됩니다.\n정규식을 기반으로 하는 라우트 경로의 예:\n다음의 라우트 경로는 라우트 이름에 “a”가 포함된 모든 항목과 일치합니다.</p>\n<p>app.get(/a/, function(req, res) {\nres.send('/a/');\n});\n다음의 라우트 경로는 butterfly 및 dragonfly와 일치하지만, butterflyman 및 dragonfly man 등과 일치하지 않습니다.</p>\n<p>app.get(/.<em>fly$/, function(req, res) {\nres.send('/.</em>fly$/');\n});\n라우트 핸들러\n미들웨어와 비슷하게 작동하는 여러 콜백 함수를 제공하여 요청을 처리할 수 있습니다. 유일한 차이점은 이러한 콜백은 next('route')를 호출하여 나머지 라우트 콜백을 우회할 수도 있다는 점입니다. 이러한 메커니즘을 이용하면 라우트에 대한 사전 조건을 지정한 후, 현재의 라우트를 계속할 이유가 없는 경우에는 제어를 후속 라우트에 전달할 수 있습니다.\n다음 예에 나타난 것과 같이, 라우트 핸들러는 함수나 함수 배열의 형태 또는 둘을 조합한 형태일 수 있습니다.\n하나의 콜백 함수는 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다.</p>\n<p>app.get('/example/a', function (req, res) {\nres.send('Hello from A!');\n});\n2개 이상의 콜백 함수는 하나의 라우트를 처리할 수 있습니다(next 오브젝트를 반드시 지정해야 함). 예를 들면 다음과 같습니다.</p>\n<p>app.get('/example/b', function (req, res, next) {\nconsole.log('the response will be sent by the next function ...');\nnext();\n}, function (req, res) {\nres.send('Hello from B!');\n});\n하나의 콜백 함수 배열은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다.</p>\n<p>var cb0 = function (req, res, next) {\nconsole.log('CB0');\nnext();\n}\nvar cb1 = function (req, res, next) {\nconsole.log('CB1');\nnext();\n}\nvar cb2 = function (req, res) {\nres.send('Hello from C!');\n}\napp.get('/example/c', [cb0, cb1, cb2]);\n독립적인 함수와 함수 배열의 조합은 하나의 라우트를 처리할 수 있습니다. 예를 들면 다음과 같습니다.</p>\n<p>var cb0 = function (req, res, next) {\nconsole.log('CB0');\nnext();\n}\nvar cb1 = function (req, res, next) {\nconsole.log('CB1');\nnext();\n}\napp.get('/example/d', [cb0, cb1], function (req, res, next) {\nconsole.log('the response will be sent by the next function ...');\nnext();\n}, function (req, res) {\nres.send('Hello from D!');\n});\n응답 메소드\n다음 표에 표시된 응답 오브젝트에 대한 메소드(res)는 응답을 클라이언트로 전송하고 요청-응답 주기를 종료할 수 있습니다. 라우트 핸들러로부터 다음 메소드 중 어느 하나도 호출되지 않는 경우, 클라이언트 요청은 정지된 채로 방치됩니다.\n메소드 설명\nres.download() 파일이 다운로드되도록 프롬프트합니다.\nres.end() 응답 프로세스를 종료합니다.\nres.json() JSON 응답을 전송합니다.\nres.jsonp() JSONP 지원을 통해 JSON 응답을 전송합니다.\nres.redirect() 요청의 경로를 재지정합니다.\nres.render() 보기 템플리트를 렌더링합니다.\nres.send() 다양한 유형의 응답을 전송합니다.\nres.sendFile 파일을 옥텟 스트림의 형태로 전송합니다.\nres.sendStatus() 응답 상태 코드를 설정한 후 해당 코드를 문자열로 표현한 내용을 응답 본문으로서 전송합니다.\napp.route()\napp.route()를 이용하면 라우트 경로에 대하여 체인 가능한 라우트 핸들러를 작성할 수 있습니다. 경로는 한 곳에 지정되어 있으므로, 모듈식 라우트를 작성하면 중복성과 오타가 감소하여 도움이 됩니다. 라우트에 대한 자세한 정보는 Router() 문서를 참조하십시오.\napp.route()를 사용하여 정의된 체인 라우트 핸들러의 예는 다음과 같습니다.</p>\n<p>app.route('/book')\n.get(function(req, res) {\nres.send('Get a random book');\n})\n.post(function(req, res) {\nres.send('Add a book');\n})\n.put(function(req, res) {\nres.send('Update the book');\n});\nexpress.Router\nexpress.Router 클래스를 사용하면 모듈식 마운팅 가능한 핸들러를 작성할 수 있습니다. Router 인스턴스는 완전한 미들웨어이자 라우팅 시스템이며, 따라서 “미니 앱(mini-app)”이라고 불리는 경우가 많습니다.\n다음 예에서는 라우터를 모듈로서 작성하고, 라우터 모듈에서 미들웨어 함수를 로드하고, 몇몇 라우트를 정의하고, 기본 앱의 한 경로에 라우터 모듈을 마운트합니다.\n다음의 내용이 입력된 birds.js라는 이름의 라우터 파일을 앱 디렉토리에 작성하십시오.</p>\n<p>var express = require('express');\nvar router = express.Router();\n// middleware that is specific to this router\nrouter.use(function timeLog(req, res, next) {\nconsole.log('Time: ', Date.now());\nnext();\n});\n// define the home page route\nrouter.get('/', function(req, res) {\nres.send('Birds home page');\n});\n// define the about route\nrouter.get('/about', function(req, res) {\nres.send('About birds');\n});\nmodule.exports = router;\n이후 앱 내에서 다음과 같이 라우터 모듈을 로드하십시오.</p>\n<p>var birds = require('./birds');\n...\napp.use('/birds', birds);\n앱은 이제 /birds 및 /birds/about에 대한 요청을 처리할 수 있게 되었으며, 해당 라우트에 대한 특정한 미들웨어 함수인 timeLog를 호출할 것입니다.</p>\n<p>출처: <a href=\"https://expressjs.com/ko/guide/routing.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\">https://expressjs.com/ko/guide/routing.html</a></p>","excerpt":"Hello world 예제\n기본적으로 이 앱은 여러분이 작성할 수 있는 가장 간단한 Express 앱일 것입니다. 이 앱은 하나의 파일로 된 앱이며 Express 생성기를 통해 얻게 되는 앱과는 같지 않습니다. (이 예제와 달리 Express 생성기…","tableOfContents":"","fields":{"slug":"/Express-study_1/"},"frontmatter":{"title":"Express guide","date":"Sep 20, 2021","tags":["express"],"keywords":["Dev.seungwon Jang","seungwon Jang"],"update":"Sep 20, 2021"}}},"pageContext":{"slug":"/Express-study_1/","series":[{"slug":"/Express-study_1/","title":"Express guide","num":1}],"lastmod":"2021-09-20"}},"staticQueryHashes":["2027115977","694178885"]}